// 标签页管理功能
function initTabFunctions(app) {
    // 扩展HttpRequestTool类，添加标签页相关方法
    Object.assign(app, {
        createNewTab() {
            const newId = Math.max(...this.tabs.keys()) + 1;
            const uniqueId = this.generateUniqueId();
            const newTab = {
                id: newId,
                uniqueId: uniqueId,
                name: '未命名',
                method: 'GET',
                url: '',
                headers: {
                    'Content-Type': 'application/json'
                },
                params: {},
                body: '',
                options: this.getDefaultOptions(),
                response: null // 新增：存储该标签页的响应数据
            };

            this.tabs.set(newId, newTab);
            this.currentTab = newId;
            this.updateTabsDisplay();
            this.loadTabData(newTab);
            this.saveAllPersistent();

            // 触发新标签页创建事件，让环境选择器更新
            document.dispatchEvent(new CustomEvent('newTabCreated', { 
                detail: { tabId: newId, tab: newTab } 
            }));
        },

        updateTabsDisplay() {
            const tabsList = document.querySelector('.tabs-list');
            tabsList.innerHTML = '';

            this.tabs.forEach(tab => {
                const tabElement = document.createElement('div');
                tabElement.className = `tab ${tab.id === this.currentTab ? 'active' : ''}`;
                tabElement.dataset.tabId = tab.id;

                tabElement.innerHTML = `
                    <span class="tab-title">${tab.name}</span>
                    ${this.tabs.size > 1 ? '<button class="tab-close">×</button>' : ''}
                `;

                // 标签页点击事件
                tabElement.addEventListener('click', (e) => {
                    if (!e.target.classList.contains('tab-close') && !e.target.classList.contains('tab-title-input')) {
                        this.switchTab(tab.id);
                    }
                });

                // 标签页右键菜单事件
                tabElement.addEventListener('contextmenu', (e) => {
                    e.preventDefault();
                    this.showTabContextMenu(e, tab.id);
                });

                // 关闭按钮事件
                const closeBtn = tabElement.querySelector('.tab-close');
                if (closeBtn) {
                    closeBtn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.closeTab(tab.id);
                    });
                }

                tabsList.appendChild(tabElement);
            });
        },

        switchTab(tabId) {
            // 保存当前标签页数据
            this.saveCurrentTabData();

            // 切换到新标签页
            this.currentTab = tabId;
            this.updateTabsDisplay();

            // 加载新标签页数据
            const tab = this.tabs.get(tabId);
            this.loadTabData(tab);

            // 触发标签页切换事件，让环境选择器更新
            document.dispatchEvent(new CustomEvent('tabChanged', { 
                detail: { tabId: tabId, tab: tab } 
            }));
        },

        closeTab(tabId) {
            if (this.tabs.size <= 1) return;

            this.tabs.delete(tabId);

            if (this.currentTab === tabId) {
                this.currentTab = this.tabs.keys().next().value;
            }

            this.updateTabsDisplay();
            const tab = this.tabs.get(this.currentTab);
            this.loadTabData(tab);
            this.saveAllPersistent();
        },

        duplicateTab(tabId) {
            const sourceTab = this.tabs.get(tabId);
            if (!sourceTab) return;

            // 创建新标签页，使用数字ID保持一致性
            const newTabId = Math.max(...this.tabs.keys()) + 1;
            const uniqueId = this.generateUniqueId();
            const newTab = {
                id: newTabId,
                uniqueId: uniqueId,
                name: sourceTab.name + ' (副本)',
                method: sourceTab.method,
                url: sourceTab.url,
                headers: JSON.parse(JSON.stringify(sourceTab.headers)), // 深拷贝
                body: sourceTab.body,
                options: JSON.parse(JSON.stringify(sourceTab.options)), // 深拷贝
                response: null // 新增：复制的标签页初始化为无响应数据
            };

            // 添加到标签页集合
            this.tabs.set(newTabId, newTab);
            
            // 切换到新标签页
            this.currentTab = newTabId;
            
            // 更新显示
            this.updateTabsDisplay();
            this.loadTabData(newTab);
            this.saveAllPersistent();

            // 触发新标签页创建事件，让环境选择器更新
            document.dispatchEvent(new CustomEvent('newTabCreated', { 
                detail: { tabId: newTabId, tab: newTab } 
            }));
        },

        saveCurrentTabData() {
            const tab = this.tabs.get(this.currentTab);
            if (!tab) return;

            const methodSelect = document.getElementById('method-select');
            const urlInput = document.getElementById('url-input');
            const bodyTextarea = document.getElementById('body-textarea');

            tab.method = methodSelect ? methodSelect.value : 'GET';
            tab.url = urlInput ? urlInput.value : '';
            tab.body = bodyTextarea ? bodyTextarea.value : '';

            // 保存请求头
            tab.headers = {};
            document.querySelectorAll('.header-row').forEach(row => {
                const keyInput = row.querySelector('.header-key');
                const valueInput = row.querySelector('.header-value');
                if (keyInput && valueInput) {
                    const key = keyInput.value.trim();
                    const value = valueInput.value.trim();
                    if (key && value) {
                        tab.headers[key] = value;
                    }
                }
            });

            // 保存查询参数
            tab.params = {};
            document.querySelectorAll('.param-row').forEach(row => {
                const keyInput = row.querySelector('.param-key');
                const valueInput = row.querySelector('.param-value');
                if (keyInput && valueInput) {
                    const key = keyInput.value.trim();
                    const value = valueInput.value.trim();
                    if (key) {
                        tab.params[key] = value;
                    }
                }
            });

            // 保存高级选项
            tab.options = this.getCurrentOptions();
            this.saveAllPersistent();
        },

        loadTabData(tab) {
            const methodSelect = document.getElementById('method-select');
            const urlInput = document.getElementById('url-input');
            const bodyTextarea = document.getElementById('body-textarea');

            if (methodSelect) methodSelect.value = tab.method;
            if (urlInput) urlInput.value = tab.url;
            if (bodyTextarea) bodyTextarea.value = tab.body;

            // 加载请求头
            this.loadHeaders(tab.headers);

            // 加载查询参数
            if (tab.params) {
                this.loadParams(tab.params);
            } else {
                // 如果没有保存的参数，从URL中解析
                const params = this.parseUrlParams(tab.url);
                this.loadParams(params);
            }

            // 加载高级选项，优先显示tab.options.sm4Key/sm4IV
            this.loadOptions(tab.options);
            if (tab.options && tab.options.sm4Key !== undefined) {
                document.getElementById('sm4-key').value = tab.options.sm4Key;
            }
            if (tab.options && tab.options.sm4IV !== undefined) {
                document.getElementById('sm4-iv').value = tab.options.sm4IV;
            }

            // 加载该标签页的响应数据
            if (tab.response) {
                // 检查是否是错误响应
                if (tab.response.error) {
                    this.displayResponse(tab.response);
                } else {
                    this.displayResponse(tab.response);
                }
            } else {
                // 如果没有响应数据，清空响应区域
                this.clearResponseArea();
            }

            this.saveAllPersistent();
        },

        loadHeaders(headers) {
            const headersList = document.getElementById('headers-list');
            headersList.innerHTML = '';

            // 添加现有请求头
            Object.entries(headers).forEach(([key, value]) => {
                this.addHeaderRow(key, value);
            });

            // 如果没有请求头，添加默认的Content-Type请求头
            if (Object.keys(headers).length === 0) {
                this.addHeaderRow('Content-Type', 'application/json');
            }
        },

        addHeaderRow(key = '', value = '') {
            const headersList = document.getElementById('headers-list');
            const row = document.createElement('div');
            row.className = 'header-row';
            row.innerHTML = `
                <input type="text" class="header-key" placeholder="Content-Type" value="${key}">
                <input type="text" class="header-value" placeholder="application/json" value="${value}">
                <button class="btn-remove">删除</button>
            `;

            row.querySelector('.btn-remove').addEventListener('click', () => {
                row.remove();
            });

            headersList.appendChild(row);
            this.saveAllPersistent();
        },

        addParamRow(key = '', value = '') {
            const paramsList = document.getElementById('params-list');
            const paramRow = document.createElement('div');
            paramRow.className = 'param-row';
            
            paramRow.innerHTML = `
                <input type="text" class="param-key" placeholder="参数名" value="${key}">
                <input type="text" class="param-value" placeholder="参数值" value="${value}">
                <button class="btn-remove">删除</button>
            `;
            
            // 添加删除按钮事件
            paramRow.querySelector('.btn-remove').addEventListener('click', () => {
                paramRow.remove();
                this.updateUrlFromParams();
            });
            
            // 添加输入框变化事件
            paramRow.querySelector('.param-key').addEventListener('input', () => this.updateUrlFromParams());
            paramRow.querySelector('.param-value').addEventListener('input', () => this.updateUrlFromParams());
            
            paramsList.appendChild(paramRow);
            
            // 如果是空行，自动聚焦到键输入框
            if (!key && !value) {
                paramRow.querySelector('.param-key').focus();
            }
        },

        loadParams(params) {
            const paramsList = document.getElementById('params-list');
            paramsList.innerHTML = '';
            
            for (const [key, value] of Object.entries(params)) {
                this.addParamRow(key, value);
            }
            
            // 如果没有参数，添加一个空行
            if (Object.keys(params).length === 0) {
                this.addParamRow();
            }
        },

        updateUrlFromParams() {
            const urlInput = document.getElementById('url-input');
            const currentUrl = urlInput.value;
            
            // 分离基础URL和查询参数
            const [baseUrl] = currentUrl.split('?');
            
            // 收集所有参数
            const params = {};
            document.querySelectorAll('.param-row').forEach(row => {
                const key = row.querySelector('.param-key').value.trim();
                const value = row.querySelector('.param-value').value.trim();
                if (key) {
                    params[key] = value;
                }
            });
            
            // 构建新的URL
            let newUrl = baseUrl;
            const paramEntries = Object.entries(params);
            if (paramEntries.length > 0) {
                const queryString = paramEntries
                    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                    .join('&');
                newUrl = `${baseUrl}?${queryString}`;
            }
            
            urlInput.value = newUrl;
            
            // 不要因为查询参数变化而更新标签页名称
            // 标签页名称应该只在用户手动修改URL基础部分时才更新
        },

        parseUrlParams(url) {
            const params = {};
            try {
                const urlObj = new URL(url);
                urlObj.searchParams.forEach((value, key) => {
                    params[key] = value;
                });
            } catch (e) {
                // 如果URL格式不正确，尝试手动解析查询参数
                const queryStart = url.indexOf('?');
                if (queryStart !== -1) {
                    const queryString = url.substring(queryStart + 1);
                    queryString.split('&').forEach(param => {
                        const [key, value] = param.split('=');
                        if (key) {
                            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
                        }
                    });
                }
            }
            return params;
        },

        updateParamsFromUrl() {
            const urlInput = document.getElementById('url-input');
            if (!urlInput) return;
            
            const url = urlInput.value;
            const params = this.parseUrlParams(url);
            
            // 清空现有参数行
            const paramsList = document.getElementById('params-list');
            if (!paramsList) return;
            
            paramsList.innerHTML = '';
            
            // 重新加载参数
            for (const [key, value] of Object.entries(params)) {
                this.addParamRow(key, value);
            }
            
            // 如果没有参数，添加一个空行
            if (Object.keys(params).length === 0) {
                this.addParamRow();
            }
        },

        getCurrentOptions() {
            const getElementValue = (id, defaultValue = '') => {
                const element = document.getElementById(id);
                return element ? element.value : defaultValue;
            };

            const getElementChecked = (id, defaultValue = false) => {
                const element = document.getElementById(id);
                return element ? element.checked : defaultValue;
            };

            return {
                addTimestamp: getElementChecked('add-timestamp'),
                timestampField: getElementValue('timestamp-field', 'timestamp'),
                timestampPos: getElementValue('timestamp-pos', 'query'),
                timestampUnit: getElementValue('timestamp-unit', 'milliseconds'),  // 新增：时间戳单位
                addNonce: getElementChecked('add-nonce'),
                nonceField: getElementValue('nonce-field', 'nonce'),
                noncePos: getElementValue('nonce-pos', 'query'),
                nonceLength: parseInt(getElementValue('nonce-length', '16')) || 16,
                addAppId: getElementChecked('add-appid'),
                appIdField: getElementValue('appid-field', 'appId'),
                appIdPos: getElementValue('appid-pos', 'query'),
                appIdValue: getElementValue('appid-value'),
                addSignature: getElementChecked('add-signature'),
                signatureField: getElementValue('signature-field', 'signature'),
                signaturePos: getElementValue('signature-pos', 'query'),
                signatureKey: getElementValue('signature-key'),
                useCustomSignature: getElementChecked('use-custom-signature'),
                customSignatureCode: getElementValue('custom-signature-code-local'),
                encryptBody: getElementChecked('encrypt-body'),
                decryptResponse: getElementChecked('decrypt-response'),
                sm4Key: getElementValue('sm4-key'),
                sm4IV: getElementValue('sm4-iv')
            };
        },

        loadOptions(options) {
            const setElementValue = (id, value) => {
                const element = document.getElementById(id);
                if (element) element.value = value;
            };

            const setElementChecked = (id, checked) => {
                const element = document.getElementById(id);
                if (element) element.checked = checked;
            };

            setElementChecked('add-timestamp', options.addTimestamp);
            setElementValue('timestamp-field', options.timestampField);
            setElementValue('timestamp-pos', options.timestampPos);
            setElementValue('timestamp-unit', options.timestampUnit || 'milliseconds');  // 新增：时间戳单位
            setElementChecked('add-nonce', options.addNonce);
            setElementValue('nonce-field', options.nonceField);
            setElementValue('nonce-pos', options.noncePos);
            setElementValue('nonce-length', options.nonceLength);
            setElementChecked('add-appid', options.addAppId);
            setElementValue('appid-field', options.appIdField);
            setElementValue('appid-pos', options.appIdPos);
            setElementValue('appid-value', options.appIdValue);
            setElementChecked('add-signature', options.addSignature);
            setElementValue('signature-field', options.signatureField);
            setElementValue('signature-pos', options.signaturePos);
            setElementValue('signature-key', options.signatureKey);
            setElementChecked('use-custom-signature', options.useCustomSignature);
            setElementValue('custom-signature-code-local', options.customSignatureCode);

            // 根据自定义签名配置状态显示/隐藏配置区域
            this.toggleCustomSignatureConfig();
            setElementChecked('encrypt-body', options.encryptBody);
            setElementChecked('decrypt-response', options.decryptResponse);
            setElementValue('sm4-key', options.sm4Key);
            setElementValue('sm4-iv', options.sm4IV);
            this.saveAllPersistent();
        },

        // 更新当前标签页名称
        updateCurrentTabName(url) {
            const tab = this.tabs.get(this.currentTab);
            if (!tab) return;

            // 如果是已保存的标签页（有filename字段），不重置名称
            if (tab.filename) {
                return;
            }

            const newName = this.extractTabNameFromUrl(url);
            if (newName !== tab.name) {
                tab.name = newName;
                this.updateTabsDisplay();
            }
        },
        
        // 获取当前标签页的数据参数（用于多环境切换）
        getCurrentTabDataParams() {
            const tab = this.tabs.get(this.currentTab);
            if (!tab) return {};
            
            // 保存当前标签页的所有相关数据
            const params = {
                headers: {},
                params: {},
                options: this.getCurrentOptions(),
                body: document.getElementById('body-textarea')?.value || '',
                url: document.getElementById('url-input')?.value || ''
            };
            
            // 获取请求头
            document.querySelectorAll('.header-row').forEach(row => {
                const keyInput = row.querySelector('.header-key');
                const valueInput = row.querySelector('.header-value');
                if (keyInput && valueInput) {
                    const key = keyInput.value.trim();
                    const value = valueInput.value.trim();
                    if (key && value) {
                        params.headers[key] = value;
                    }
                }
            });
            
            // 获取查询参数
            document.querySelectorAll('.param-row').forEach(row => {
                const keyInput = row.querySelector('.param-key');
                const valueInput = row.querySelector('.param-value');
                if (keyInput && valueInput) {
                    const key = keyInput.value.trim();
                    const value = valueInput.value.trim();
                    if (key) {
                        params.params[key] = value;
                    }
                }
            });
            
            return params;
        },
        
        // 设置标签页的数据参数（用于多环境切换）
        setTabDataParams(params) {
            // 设置URL
            const urlInput = document.getElementById('url-input');
            if (urlInput) urlInput.value = params.url || '';
            
            // 设置请求体
            const bodyTextarea = document.getElementById('body-textarea');
            if (bodyTextarea) bodyTextarea.value = params.body || '';
            
            // 设置请求头
            if (params.headers) {
                this.loadHeaders(params.headers);
            }
            
            // 设置查询参数
            if (params.params) {
                this.loadParams(params.params);
            }
            
            // 设置高级选项
            if (params.options) {
                this.loadOptions(params.options);
            }
        }
    });

    // 初始化标签页显示
    app.updateTabsDisplay();
}

// 导出函数以便在其他文件中使用
window.initTabFunctions = initTabFunctions;